// 系统管理相关接口
import { getFileContext, setFileContext, doPagination, responseStatus, addOneData, getDataByKey, updateOneData, removeOneData } from './util'
import { roleFile as filePath, managerFile, permissionFile } from './filePath'
import dayjs from 'dayjs'
export default [
  {
    url: '/api/system/role/list',
    method: 'get',
    timeout: 200,
    response: ({ query }) => {
      const data = getFileContext(filePath)
      const res = query.pageSize ? doPagination(data.reverse(), query.page, query.pageSize) : data.reverse()
      return {
        ...responseStatus(),
        data: res,
        total: data.length
      }
    }
  },
  {
    url: '/api/system/role/info',
    method: 'get',
    timeout: 200,
    response: ({ query }) => {
      const data = getFileContext(filePath)
      const res = getDataByKey(data, Number(query.id))
      return {
        ...responseStatus(),
        data: res
      }
    }
  },
  {
    url: '/api/system/role/add',
    method: 'post',
    timeout: 2000,
    response: ({ body }) => {
      const data = getFileContext(filePath)
      body.createTime = dayjs().format('YYYY-MM-DD hh:mm:ss')
      const res = getDataByKey(data, body.name, 'name')
      if (res) {
        return {
          ...responseStatus(2),
          msg: '已存在相同名称的角色'
        }
      } else {
        addOneData(data, body)
        setFileContext(filePath, data)
        return {
          ...responseStatus(),
          msg: '新增成功'
        }
      }
    }
  },
  {
    url: '/api/system/role/update',
    method: 'post',
    timeout: 200,
    response: ({ body }) => {
      const data = getFileContext(filePath)
      updateOneData(data, body)
      setFileContext(filePath, data)
      return {
        ...responseStatus()
      }
    }
  },
  {
    url: '/api/system/role/remove',
    method: 'post',
    timeout: 200,
    response: ({ body }) => {
      const data = getFileContext(filePath)
      const managerList = getFileContext(managerFile)
      const manager = managerList.find(item => item.role === Number(body.id))
      console.log(managerList, body.id)
      if (manager) {
        return {
          ...responseStatus(2),
          msg: '角色存在绑定管理员，不可删除'
        }
      }
      removeOneData(data, body.id)
      setFileContext(filePath, data)
      return {
        ...responseStatus()
      }
    }
  },
  {
    url: '/api/system/role/permissions',
    method: 'get',
    timeout: 200,
    response: () => {
      const data = getFileContext(permissionFile)
      return {
        ...responseStatus(),
        data
      }
    }
  }
]
